package top.blackr.folivora.common.pay.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.http.HttpRequest;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author BlackR
 */
@Slf4j
public class WxRobotUtil {

    private static final String WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=%s";
    private static final String EXCEPTION = "5de******************************986";

    public static void sendException(String payType, Throwable throwable) {
        String message = throwable.getMessage();
        StackTraceElement[] stackTrace = throwable.getStackTrace();
        String stackTraceStr = Arrays.stream(stackTrace)
                .filter(stackTraceElement -> stackTraceElement.getClassName().contains("com.xary."))
                .map(stackTraceElement -> {
                    String className = stackTraceElement.getClassName();
                    String methodName = stackTraceElement.getMethodName();
                    int lineNumber = stackTraceElement.getLineNumber();
                    return String.format("         >第%s行:<font color=\\\"comment\\\">%s.%s</font>", lineNumber, className, methodName);
                }).collect(Collectors.joining("\n"));
        if (StrUtil.isEmptyIfStr(stackTraceStr)) {
            stackTraceStr = "         >无堆栈信息:<font color=\\\"comment\\\">其他异常</font>";
        }
        String content = String.format("{\n" +
                "    \"msgtype\": \"markdown\",\n" +
                "    \"markdown\": {\n" +
                "        \"content\": \"<font color=\\\"warning\\\">%s</font>\n" +
                "%s\"" +
                "    }\n" +
                "}", (payType + "回调异常:" + message), stackTraceStr);
        send(content);
    }

    private static void send(String content) {
        try {
            HttpRequest.post(String.format(WEBHOOK_URL, WxRobotUtil.EXCEPTION))
                    .bodyString(content)
                    .execute()
                    .onFailed((request, e) -> log.warn("异常信息推送失败" + "\n" + e.getResponse().asString()));
        } catch (Exception ignored) {
        }
    }
}
